import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import type { DataTableColumn } from 'naive-ui'

export type ResizableColumn = DataTableColumn & {
  width?: number
  minWidth?: number
  maxWidth?: number
  resizable?: boolean
}

export interface UseResizableColumnsOptions {
  columns: ResizableColumn[]
  tableKey: string
  defaultWidths?: Record<string, number>
}

export function useResizableColumns(options: UseResizableColumnsOptions) {
  const { columns, tableKey, defaultWidths = {} } = options
  
  // 存储列宽状态
  const columnWidths = ref<Record<string, number>>({...defaultWidths})
  const isResizing = ref(false)
  const currentResizeColumn = ref<string>('')
  const resizeStartX = ref(0)
  const resizeStartWidth = ref(0)
  
  // 从localStorage加载保存的列宽
  const loadColumnWidths = () => {
    try {
      const saved = localStorage.getItem(`table-columns-${tableKey}`)
      if (saved) {
        const savedWidths = JSON.parse(saved)
        columnWidths.value = { ...defaultWidths, ...savedWidths }
      }
    } catch (e) {
      console.warn('Failed to load column widths from localStorage:', e)
      columnWidths.value = { ...defaultWidths }
    }
  }
  
  // 保存列宽到localStorage
  const saveColumnWidths = () => {
    try {
      localStorage.setItem(`table-columns-${tableKey}`, JSON.stringify(columnWidths.value))
    } catch (e) {
      console.warn('Failed to save column widths to localStorage:', e)
    }
  }
  
  // 开始调整列宽
  const startResize = (event: MouseEvent, columnKey: string) => {
    if (!columnKey) return
    
    event.preventDefault()
    event.stopPropagation()
    
    isResizing.value = true
    currentResizeColumn.value = columnKey
    resizeStartX.value = event.clientX
    resizeStartWidth.value = columnWidths.value[columnKey] || 120
    
    // console.log('🎯 开始调整列宽:', columnKey, '当前宽度:', resizeStartWidth.value)
    
    document.addEventListener('mousemove', handleMouseMove, { passive: false })
    document.addEventListener('mouseup', handleMouseUp)
    document.body.style.cursor = 'col-resize'
    document.body.style.userSelect = 'none'
  }
  
  // 处理鼠标移动
  const handleMouseMove = (event: MouseEvent) => {
    if (!isResizing.value || !currentResizeColumn.value) return
    
    event.preventDefault()
    const deltaX = event.clientX - resizeStartX.value
    const newWidth = Math.max(50, resizeStartWidth.value + deltaX)
    
    // 应用宽度限制
    const column = columns.find(col => 'key' in col && col.key === currentResizeColumn.value)
    if (column) {
      const minWidth = column.minWidth || 50
      const maxWidth = column.maxWidth || 500
      const constrainedWidth = Math.max(minWidth, Math.min(maxWidth, newWidth))
      
      columnWidths.value[currentResizeColumn.value] = constrainedWidth
      // console.log('📏 调整列宽:', currentResizeColumn.value, '新宽度:', constrainedWidth)
    }
  }
  
  // 处理鼠标释放
  const handleMouseUp = () => {
    if (isResizing.value) {
      saveColumnWidths()
      // console.log('💾 调整完成，保存列宽')
      
      // 拖拽结束后不需要重置颜色，因为颜色不会改变
      // console.log('💾 调整结束:', currentResizeColumn.value)
    }
    
    isResizing.value = false
    currentResizeColumn.value = ''
    
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    document.body.style.cursor = ''
    document.body.style.userSelect = ''
  }
  
  // 重置所有列宽
  const resetColumnWidths = () => {
    // console.log('🔄 重置列宽到默认值')
    columnWidths.value = { ...defaultWidths }
    saveColumnWidths()
  }
  
  // 动态添加调整手柄到表头
  const addResizeHandlesToTable = () => {
    nextTick(() => {
      // console.log('🔍 开始查找表头元素...')
      
      // 查找所有表头单元格
      const headerCells = document.querySelectorAll('.n-data-table-th')
      // console.log('📋 找到表头单元格数量:', headerCells.length)
      
      headerCells.forEach((cell, index) => {
        // 避免最后一列添加调整手柄
        if (index >= columns.length - 1) return
        
        const column = columns[index]
        if (!column || column.resizable === false || !('key' in column)) return
        
        const key = column.key as string
        
        // 检查是否已经添加了调整手柄
        if (cell.querySelector('.resize-handle-container')) return
        
        // console.log('➕ 为列添加调整手柄:', key)
        
        // 创建调整手柄容器（扩大触发区域）
        const handleContainer = document.createElement('div')
        handleContainer.className = 'resize-handle-container'
        handleContainer.setAttribute('data-column', key)
        handleContainer.style.cssText = `
          position: absolute;
          right: -4px;
          top: 0;
          width: 8px;
          height: 100%;
          cursor: col-resize;
          z-index: 9999;
          display: flex;
          align-items: center;
          justify-content: center;
        `
        
        // 创建可视的调整手柄
        const handle = document.createElement('div')
        handle.className = 'resize-handle-visual'
        handle.style.cssText = `
          width: 2.5px;
          height: 40%;
          background-color: #cccccc;
          border-radius: 1px;
          opacity: 1;
          pointer-events: none;
        `
        
        // 添加事件监听器到容器（扩大的触发区域）
        handleContainer.addEventListener('mousedown', (e) => {
          // console.log('🖱️ 点击调整手柄:', key)
          startResize(e as MouseEvent, key)
        })
        
        handleContainer.addEventListener('mouseenter', () => {
          // console.log('✨ 鼠标进入调整区域:', key)
        })
        
        handleContainer.addEventListener('mouseleave', () => {
          // 移除颜色变化，保持一致样式
        })
        
        // 将可视手柄添加到容器中
        handleContainer.appendChild(handle)
        
        // 确保表头单元格是相对定位的
        const cellElement = cell as HTMLElement
        cellElement.style.position = 'relative'
        cellElement.style.overflow = 'visible'
        
        // 添加手柄容器到表头单元格
        cellElement.appendChild(handleContainer)
        
        // console.log('✅ 成功添加调整手柄到列:', key)
      })
    })
  }
  
  // 创建带调整功能的列配置（简化版，只设置宽度）
  const resizableColumns = computed(() => {
    return columns.map((column) => {
      if ('key' in column) {
        const key = column.key as string
        const currentWidth = columnWidths.value[key] || column.width || 120
        
        return {
          ...column,
          width: currentWidth
        }
      }
      return {
        ...column
      }
    })
  })
  
  // 初始化
  onMounted(() => {
    loadColumnWidths()
    // console.log('🚀 列宽调整功能初始化完成，表格键:', tableKey)
    
    // 延迟添加调整手柄，确保表格已经渲染
    setTimeout(() => {
      addResizeHandlesToTable()
      
      // 设置定期检查，以防表格重新渲染
      const checkInterval = setInterval(() => {
        const existingHandles = document.querySelectorAll('.resize-handle-container')
        if (existingHandles.length === 0) {
          // console.log('🔄 检测到表格重新渲染，重新添加调整手柄')
          addResizeHandlesToTable()
        }
      }, 1000)
      
      // 5秒后停止定期检查
      setTimeout(() => {
        clearInterval(checkInterval)
        // console.log('⏰ 停止定期检查')
      }, 5000)
    }, 500)
  })
  
  onBeforeUnmount(() => {
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
  })
  
  return {
    columnWidths: computed(() => columnWidths.value),
    resizableColumns,
    isResizing: computed(() => isResizing.value),
    resetColumnWidths
  }
}
